package com.woniu.mealsService.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.exception.meals.FeignException;
import com.woniu.exception.meals.OrderException;
import com.woniu.mealsService.data.OrderStatus;
import com.woniu.mealsService.mapper.OrderProductMapper;
import com.woniu.mealsService.model.OrderProduct;
import com.woniu.mealsService.service.impl.OrderProductServiceImpl;
import com.woniu.user.client.UserFeignClient;
import com.woniu.user.dto.UserInfoFeignDto;
import com.woniu.utils.EnumException;
import com.woniu.utils.Result;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiang
 */
@Component
// 消费者用户2分钟一次查询订单支付宝支付状态

public class AlipayConsumer {
    @Autowired
    private OrderProductServiceImpl orderProductService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay_alipay_query"),
            exchange = @Exchange(name = "delay_Update_alipayquery"),
            key = "alipay"
    ))
    @RabbitHandler
    public void updateOrder(String orderId)  throws Exception{
        try {
            LambdaQueryWrapper<OrderProduct> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderProduct::getOrderId,orderId);
            OrderProduct orderProduct = orderProductMapper.selectOne(queryWrapper);
            if (null == orderProduct){
                throw new OrderException(EnumException.ORDER_NULL_EXCEPTION);
            }
            String msg = orderProductService.alipayQuery(orderId);
            if ("WAIT_BUYER_PAY".equals(msg)) {
                rabbitTemplate.convertAndSend("delay_alipay_status", orderId);
            }else if ("TRADE_SUCCESS".equals(msg)){
                orderProductService.updateOrder(orderId, OrderStatus.ORDER_PAID);
            }else if ("TRADE_FINISHED".equals(msg)){
                orderProductService.closeOrder(orderId);
            }else {
                orderProductService.cancelOrder(orderId,orderProduct.getUserId(),"学生");
            }
        }catch (Exception e){
            throw e;
        }
    }
}
